package org.enlongWu.controller;

import org.enlongWu.pojo.*;
import org.enlongWu.service.*;
import org.enlongWu.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired//消息类型 列表获取
    private MessageTypeService messageTypeService;

    @Autowired
    private MessageService messageService;

    @Autowired//申请状态 列表获取
    private ApplicationService applicationService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    /**
     * 发送消息
     * @param message
     * @return
     */
    @PostMapping("/send")
    public Result send(@RequestBody @Validated Message message) {
        System.out.println(message);
        messageService.add(message);
        return Result.success();
    }

    //当前用户，（接收端）消息列表，条件分页
    @GetMapping("/list")
    public Result<PageBean<Message>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer messageType,
            @RequestParam(required = false) String state
    ) {
        PageBean<Message> pb =  messageService.list(pageNum,pageSize,messageType,state);
        return Result.success(pb);
    }


    /**
     * 当前用户的申请权限，并向所有管理员用户通知
     * @param newRole 想申请的权限
     * @return
     */
    @PostMapping("/apply")
    public Result Apply(String newRole){
        //1拿到当前用户信息
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        //2生成申请，并新增
        LocalDateTime now = LocalDateTime.now();
        Application application = new Application();
        application.setOldRole(loginUser.getRole());
        application.setNewRole(newRole);
        application.setState("waiting");
        application.setCreateTime(now);
        //在这里新增申请
        applicationService.addApplication(application);
        System.out.println(application);
        //3获取管理用户列表，即具备核实权限的用户
        //预设查找的权限对象要求
        Role searchModel = new Role();
        searchModel.setPrivilegesManage(1);//能核实的用户
        //拿到具有如PrivilegeVerify的role类型列表；
        List<Role> roleList =  roleService.findPrivilegeRoles(searchModel);
        System.out.println(roleList);
        //获取对应的用户列表
        List<User> reciverList = userService.getUserListByRoleList(roleList);
        System.out.println(reciverList);
        //4消息模本
        Message message = new Message();
        message.setMessageType(1);
        message.setCreateTime(now);
        message.setTitle("权限申请");
        message.setState("未读");
        message.setSendUser(loginUser.getId());

        for (User user : reciverList) {
            message.setContent(application.getId().toString());
            message.setReceiveUser(user.getId()/*所有管理员接收*/);
            //新增（即发送）
            messageService.add(message);
        }

        return Result.success("权限申请成功");
    }
    /**
     * 当前用户，已经发送的申请实体列表
     * @return
     */
    @GetMapping("/getApplicationList")
    public Result<PageBean<Application>> ApplicationList(
            Integer pageNum,
            Integer pageSize
    ){
        //1查询消息集合，按发送时间分组，得到的返回结果是同一拨消息所属请求，获得其contentList
        //拿到当前用户信息
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        //2拿到发送的消息，按发送时间分组，即一一对应申请实体
        List<Message> messageList = messageService.applicationGroupBySendTime(loginUser.getId());
        System.out.println(messageList);
        List<Integer> ids = new ArrayList<>();//对应的申请实体id集
        for (Message message : messageList) {
            ids.add(Integer.parseInt(message.getContent()));
        }
        //3根据message.content作id，查找Application（这样不方便利用分页查询器）
//        List<Application> resultList = new ArrayList<>();
//        for (Message message : messageList) {
//            Application application = applicationService.findById(Integer.parseInt(message.getContent()));
//            resultList.add(application);
//        }
//        System.out.println(resultList);
        PageBean<Application> pb = applicationService.listFindById(pageNum,pageSize,ids);//查询到的用户列表
        return Result.success(pb,"分页查询申请成功");
    }

    /**
     * 获取消息类型集合
     * @return  {
     *     "code": 0,
     *     "message": "查询消息类型列表成功",
     *     "data": [
     *         {
     *             "id": 1,
     *             "typeName": "请求",
     *             "createTime": null,
     *             "updateTime": null
     *         }{..}...
     *     ]
     * }
     */
    @GetMapping("/typeList")
    public Result<List<MessageType>> typeList(
    ){
        List<MessageType> ls =  messageTypeService.list();
        return Result.success(ls,"查询消息类型列表成功 by MessageController");
    }

    /**
     * 从数据库获取申请列表
     * @return
     */
    @GetMapping("/application/stateList")
    public Result<List<ApplicationState>> applicationStateList(){
        List<ApplicationState> ls =  applicationService.list();
        return Result.success(ls,"查询申请状态列表成功 by MessageController");
    }

    /**
     * 获取申请实体
     * @return
     */
    @GetMapping("/getApplication")
    public Result<Application> getApplication(@RequestParam String content){
        Integer id = Integer.parseInt(content);
        Application application =  applicationService.findById(id);
        return Result.success(application,"查询申请状态列表成功 by MessageController");
    }


    /**
     * 根据id，标记已读
     * @param messageId
     * @return
     */
    @PutMapping("/reading")
    public Result reading(Integer messageId){
        System.out.println(messageId);
        Result result = messageService.reading(messageId);
        return result;
    }

    /**
     * 删除指定消息
     * @param messageId
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(Integer messageId){
        //查找到这条信息
        Message message = messageService.findById(messageId);
        if (message.getState().equals("未读")) {
            return Result.error("消息未读，不能删除");
        }else {
            //删除这条信息
            Result result = messageService.delete(messageId);
            return result;
        }
    }

    /**
     * 删除指定申请
     * @param applicationId
     * @return
     */
    @DeleteMapping("/application/withdraw")
    public Result applicationWithDraw(Integer applicationId){
        //删除对应的申请
        int deAp = applicationService.delete(applicationId);
        //删除对应的message
        if (deAp == 1){
            int deMe = messageService.deleteByContent(applicationId);
            return Result.success(null,"撤回了申请以及"+deMe+"条消息");
        }else {
            return Result.error("没有这条申请");
        }

    }
    /**
     * 根据申请实体Application的id，修改状态为passed、rejected；也支持回溯成waiting
     */
    @PutMapping("/handleApplication")
    public Result handleApplication(Integer applicationId,String toState){
        System.out.println(applicationId+":"+toState);
        Result result = applicationService.handleApplication(applicationId,toState);
        return result;
    }
}
